package com.halachawiki.server.data;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Query;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import com.google.appengine.api.datastore.Key;
import com.halachawiki.server.Settings;
import com.halachawiki.server.data.User.Privalege;

public class UserContainer {
	static {
		init();
	}
	public static boolean init() {
		User admin = getUserByEmail(Settings.adminEmail);
		if (admin != null) {
			return true;
		}
		admin = new User(Settings.adminEmail, "abcdef", "Administrator", "Administrator", "en");
		admin.approve();
		admin.confirm();
		admin.setPrivalege(Privalege.PRIVILEGED);
		UserContainer.addUser(admin);
		return true;
	}
	public static synchronized User getUserById(Key ID) {
		EntityManager em = EMF.get().createEntityManager();
		try {
			return em.find(User.class, ID);
		} finally {
			em.close();
		}	
	}
	
	public static synchronized User getUserByEmail(String email) {
		EntityManager em = EMF.get().createEntityManager();
		try {
			Query q = em.createQuery(
					"SELECT c FROM " + User.class.getSimpleName() + " c WHERE c.email=:emailParam");
			q = q.setParameter("emailParam", email);
			q = q.setMaxResults(1);
			@SuppressWarnings("unchecked")
			List<User> results = q.getResultList();
			if (results == null || results.size() == 0)
				return null;
			return results.get(0);
		} finally {
			em.close();
		}	
	}

	// returns ID of new user
	public static synchronized boolean addUser(User newUser) {

		// TODO: This hack only works if there is one instance of the server running
		if (getUserByEmail(newUser.getEmail())!=null)
			return false;
		
		EntityManager em = EMF.get().createEntityManager();
		try {
			em.persist(newUser);
			return true;
		} finally {
			em.close();
		}
	}
	public static synchronized void userChanged(User user) {
		EntityManager em = EMF.get().createEntityManager();
		try {
			em.getTransaction().begin();
			User userx = em.find(User.class, user.getId());
			userx.copyFrom(user);
			em.getTransaction().commit();
		} finally {
			em.close();
		}		
	}
	
	public static User getLogedInUser(HttpServletRequest request) {
		HttpSession session = request.getSession();
		Key userID = (Key) session.getAttribute("userID");
		if (userID == null) {
			 return null;
		}
		return getUserById(userID);
	}
	
	public static void setLoggedInUser(User user, boolean rememberMe, HttpServletRequest request) {
		HttpSession session = request.getSession();
		if (user != null)
			session.setAttribute("userID", user.getId());
		else
			session.removeAttribute("userID");
	}
	
	public static synchronized List<User> getAllUsers() {
		EntityManager em = EMF.get().createEntityManager();
		try {
			Query q = em.createQuery(
					"SELECT c FROM " + User.class.getSimpleName() + " c ");
			@SuppressWarnings("unchecked")
			List<User> results = q.getResultList();
			List<User> copy = new ArrayList<User>(results);
			return copy;
		} finally {
			em.close();
		}	
	}
}